package com.ktjy.controller;


import com.ktjy.dto.LoginDTO;
import com.ktjy.dto.LoginUser;
import com.ktjy.pojo.SysMenu;
import com.ktjy.service.ISysMenuService;
import com.ktjy.service.ISysUserService;
import com.ktjy.service.impl.PermssionService;
import com.ktjy.service.impl.UserDetailsServiceImpl;
import com.ktjy.utils.AjaxResult;
import com.ktjy.utils.Constants;
import com.ktjy.utils.JWTUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-07-28
 */
@RestController
@RequestMapping("/api")
public class LoginController {
    @Resource
    ISysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    JWTUtil jwtUtil;
    @Autowired
    PermssionService permssionService;
    @Autowired
    ISysMenuService sysMenuService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginDTO loginDTO, HttpSession session){
        //1.判断验证码是否正确
        //1.1从redis获取验证码
        String captcha = (String)redisTemplate.opsForValue().get(Constants.CAPTCHA+loginDTO.getUuid());
        //1.2判断验证码是否为空
        if (captcha==null) {
            return AjaxResult.error("验证码已过期");
        }
        //1.3删除验证码
        redisTemplate.delete(Constants.CAPTCHA+loginDTO.getUuid());
        //1.4用户输入的验证码和redis中存储的验证码比较
        if(!captcha.equalsIgnoreCase(loginDTO.getCode())){
            return AjaxResult.error("验证码错误");
        }
        //2.查询用户是否存在
        LoginUser loginUser = null;
        try {
            loginUser = (LoginUser) userDetailsService.loadUserByUsername(loginDTO.getUsername());
        } catch (Exception e) {
            return AjaxResult.error("用户不存在");
        }
        //3.判断密码是否正确
        boolean matches = bCryptPasswordEncoder.matches(loginDTO.getPassword(), loginUser.getPassword());
        if(!matches){
            return AjaxResult.error("用户名或者密码错误");
        }
        //4.将用户信息保存到jwt盾牌
        String token = jwtUtil.generateToken(loginUser);

        return AjaxResult.success("登录成功",token);
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = (LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("username", loginUser.getUsername());
        ajax.put("avatar", loginUser.getAvatar());
        ajax.put("permissions", loginUser.getPerms());

        //查询当前登录用户能够看到的菜单
        List<SysMenu> menus=null;
        if("admin".equals(loginUser.getUsername())){
            menus=sysMenuService
                    .buildTree(sysMenuService.findMenuTreeAll(),0l);
        }else{
            menus = sysMenuService
                    .buildTree(sysMenuService.findMenuTreeByUserId(loginUser.getUserId()),0l);
        }
        ajax.put("menus", menus);

        return ajax;
    }

    @PostMapping("/logout")
    public AjaxResult logout(){
        LoginUser loginUser=(LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        redisTemplate.delete(Constants.LOGIN_USER+ loginUser.getUsername());
        return AjaxResult.success("退出成功");
    }
}
